<template>
  <div class="shell">
    <!-- <h1>个人数据</h1> -->
    <Data />
    <div v-if="mainStore.userdata.role_name!='dealer'">
      <h1>出售产品</h1>
      <div class="sell-goods-list">
        <div class="content-grid" v-loading="loadingSell" element-loading-text="加载中...">
          <div class="goods-row" v-for="index in Math.ceil(displayListSell.length / 2)" :key="index">
            <SellGoodsItem
              v-for="item in displayListSell.slice((index - 1) * 2, index * 2)"
              :key="item.product_id"
              :goods="item"
              :showDetail="true"
              :showOffShelf="true"
              :showStatus="true"
            />
          </div>
        </div>
        <el-empty 
          v-if="!loadingSell && displayListSell.length === 0"
          description="暂无数据"
        />
        <div class="pagination" v-show="totalSell > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalSell"
            :current-page="currentPageSell"
            :page-size="pageSizeSell"
            @current-change="handlePageChangeSell"
          />
        </div>
      </div>
    </div>
    <div v-if="mainStore.userdata.role_name!='farmer'">
      <h1>收购产品</h1>
      <div v-if="errorPurchase" class="error">{{ errorPurchase }}</div>
      <div v-else>
        <div class="purchase-grid" v-loading="loadingPurchase" element-loading-text="加载中...">
          <PurchaseItem 
            v-for="item in currentItemsPurchase" 
            :key="item.article_id" 
            :data="item"
            @view-detail="handleViewDetail"
            @update="handleUpdate"
          />
        </div>
        <el-empty 
          v-if="!loadingPurchase && purchaseItems.length === 0"
          description="暂无数据"
        />
        <div class="pagination" v-show="totalPurchase > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalPurchase"
            :current-page="currentPagePurchase"
            :page-size="itemsPerPagePurchase"
            @current-change="handlePageChangePurchase"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import Data from '../components/PersonalData.vue';
import SellGoodsItem from '../components/SellGoodsItem.vue'; // 引入SellGoodsItem组件
import PurchaseItem from '../components/PurchaseItem.vue'; // 引入PurchaseItem组件
import { inject } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/stores'
const router = useRouter()
const $axios = inject('$axios');


const mainStore = useMainStore();
const activeTab = ref('buy')
// 出售产品相关逻辑
const currentPageSell = ref(1);
const pageSizeSell = ref(4); // 每页显示4个产品
const totalSell = ref(0);
const loadingSell = ref(false);
const sellList = ref([]);
const buyList = ref([]);
const store = useMainStore();

// 计算显示列表
const displayListSell = computed(() => {
  const list = sellList.value;
  totalSell.value = list.length;
  const start = (currentPageSell.value - 1) * pageSizeSell.value;
  const end = start + pageSizeSell.value;
  return list.slice(start, end);
});

// 获取出售产品列表
const fetchSellGoods = async () => {
  loadingSell.value = true;
  try {
    const response = await $axios.get('/agri_products', {
      headers: {
        Authorization: localStorage.getItem('token') 
      }
    });
    if (response.data.code === 200) {
      const data = response.data.data.map(item => ({
        ...item,
        created_at: new Date(item.created_at).toLocaleString()
      }));
      sellList.value = data;
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    loadingSell.value = false;
  }
};

// 分页变化处理
const handlePageChangeSell = (page) => {
  currentPageSell.value = page;
};

// 收购产品相关逻辑
const purchaseItems = ref([]);
const errorPurchase = ref(null);
const currentPagePurchase = ref(1);
const itemsPerPagePurchase = 4; // 每页显示4个组件
const totalPurchase = ref(0); // 总条目数
const loadingPurchase = ref(true);

// 获取收购产品数据
const fetchPurchaseItems = async () => {
  try {
    const response = await $axios.get('/article', {
      headers: {
        Authorization: localStorage.getItem('token') 
      }
    });
    if (response.data.code === 200) {
      purchaseItems.value = response.data.data;
      totalPurchase.value = purchaseItems.value.length;
    } else {
      throw new Error(response.data.msg || '获取数据失败');
    }
  } catch (err) {
    errorPurchase.value = err.message || '获取数据时出错';
  } finally {
    loadingPurchase.value = false;
  }
};

// 计算当前页显示的组件
const currentItemsPurchase = computed(() => {
  const start = (currentPagePurchase.value - 1) * itemsPerPagePurchase;
  const end = start + itemsPerPagePurchase;
  return purchaseItems.value.slice(start, end);
});

// 分页变化处理
const handlePageChangePurchase = (page) => {
  currentPagePurchase.value = page;
};

// 查看详情处理
const handleViewDetail = (articleId) => {
  // 从 purchaseItems 中查找当前文章
  const currentArticle = purchaseItems.value.find(item => item.article_id === articleId)
  if (currentArticle) {
    store.setCurrentArticle(currentArticle)
    router.push(`/home/artiDetail/${articleId}`)
  } else {
    ElMessage.error('未找到文章详情')
  }
};

const handleUpdate = (updatedData) => {
  // 在 purchaseItems 数组中找到并更新对应的项
  const index = purchaseItems.value.findIndex(item => item.article_id === updatedData.article_id)
  if (index !== -1) {
    purchaseItems.value[index] = updatedData
    ElMessage.success('更新成功')
  }
}

onMounted(() => {
  fetchSellGoods();
  fetchPurchaseItems();
});
</script>

<style lang="less" scoped>
.shell {
  padding: 20px;
  width: 1200px;
  color: #000;
  h1 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #319A19;
  }
  
  .error {
    color: #f44336;
    margin: 20px 0;
  }
  
  .sell-goods-list {
    margin-top: 20px;
  }
  
  .content-grid {
    //display: grid;
    //grid-template-columns: repeat(2, 1fr);
  }
  
  .goods-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
  
  :deep(.product-item) {
    box-sizing: border-box;
    margin: 0 10px 20px 0;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .purchase-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
  }
  
}
</style>